<?php

namespace Bete\Console;

use Bete\Foundation\Application;

class Request
{

    protected $app;

    protected $params;

    protected $options;

    protected $args = [];

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function getParams()
    {
        if ($this->params === null) {
            if (isset($_SERVER['argv'])) {
                $this->params = $_SERVER['argv'];
                array_shift($this->params);
            } else {
                $this->params = [];
            }
        }

        return $this->params;
    }

    public function parseParams()
    {
        $params = $this->getParams();
        if (isset($params[0])) {
            $route = $params[0];
            array_shift($params);
        } else {
            $route = '';
        }
        
        foreach ($params as $param) {
            if (preg_match('/^--(\w+)(?:=(.*))?$/', $param, $matches)) {
                $name = $matches[1];
                $this->options[$name] = isset($matches[2]) ?
                    $matches[2] : true;
            } else {
                $this->args[] = $param;
            }
        }

        return [$route, $this->args];
    }

    public function arg($name = null, $defaultValue = null)
    {
        if ($name === null) {
            return $this->args;
        } else {
            return isset($this->args[$name]) ? 
                $this->args[$name] : $defaultValue;
        }
    }
    
    public function opt($name = null, $defaultValue = null)
    {
        if ($name === null) {
            return $this->options;
        } else {
            return isset($this->options[$name]) ?
                $this->options[$name] : $defaultValue;
        }
    }

}

